#!/usr/bin/env python
# -*- coding: utf-8 -*- 
#############################################################################
# GMangas
# Copyright (C) 2008  Ferraro Luciano (aka Lux) <luciano.ferraro@gmail.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################

import os, sys

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

import utils

files_filter = lambda path: all((not path.startswith("__init__"), path.endswith(".py")))
def find_backends(curdir):
    return [path[:-3] for path in os.listdir(os.path.join(curdir, "backends")) if files_filter(path)]

class backends_dialog:
    def __init__(self, backends, callback, curdir):
        self.root = gtk.glade.XML(os.path.join(curdir, "glade", "backends_dialog.glade"))
        self._ = self.root.get_widget("dialog")

        self.set_treeview()

        self.quitting = False        
        def run_callback(*x):
            model, iter = self.selection.get_selected()
            if not iter: return
            selected = model.get_value(iter, 1)
            self.quitting = True
            self._.destroy()
            callback(selected)
        def quit(*x):
            gtk.main_quit()
            if not self.quitting: sys.exit()
        signals = {'dialog_destroy':quit, 'exit':quit, 'start':run_callback,
                   'doubleclicked_backend':run_callback}
        self.root.signal_autoconnect(signals)

        self.load_backends(backends)
        self.start()

    def set_treeview(self):
        treeview = self.root.get_widget("treeview")
        self.liststore = gtk.ListStore(int, str)
        treeview.set_model(self.liststore)

        self.selection = treeview.get_selection()

        column = gtk.TreeViewColumn("BackEnds", gtk.CellRendererText(), text=1)
        column.set_sort_column_id(1)
        treeview.append_column(column)

    def load_backends(self, backends):
        for count, backend in enumerate(backends):
            self.liststore.append([count, backend])

    def start(self):
        self._.show_all()
        gtk.main()
